import Vue from "vue";
import Vuex from "vuex";
import { getMenuList } from "../api"
import recursionRoutes from "../utils/recursionRoutes"
import allRoutes from "../router/allRoutes"
import dynamicRoutes from "../router/dynamicRoutes";
import router from "../router";

Vue.use(Vuex);

//侧边菜单思路
//1.发送请求，获取用户菜单名
//2.通过递归函数计算出当前用户的路由配置
//3.将计算好的路由配置添加到“/”路由的children中


let userInfo=JSON.parse(localStorage.getItem('qf-userInfo')) ||{}
let permissionButtons=JSON.parse(localStorage.getItem('qf-permission-buttons')) ||{}
export default new Vuex.Store({
    state: {
        sideMenu: [],
        breadCrumb: [],
        userInfo,
        permissionButtons
    },
    mutations: {
        SET_SIDEMENU(state, payload) {
            state.sideMenu = payload
                // console.log(state.sideMenu);
                //查找到dynamicRoutes中路径为“/”的这个对象，并且给它添加一个children属性，值就是那好的sideMenu
            let target = dynamicRoutes.find(item => {
                    return item.path === "/"
                })
                // console.log("===tar", target);
                // console.log("===pay", payload);
            target.children = state.sideMenu

            //核心：通过addRoutes这个方法，动态的将路由配置添加到项目中
            router.addRoutes(dynamicRoutes)
        },
        CLEAR_SIDEMENU(state) {
            state.sideMenu = []
        },
        //更改面包屑
        SET_BREADCRUMB(state, payload) {
            state.breadCrumb = payload
        },
        SET_USERINFO(state,payload){
            state.userInfo = payload
        },
        SET_PERMISSIONBUTTONS(state,payload){
            state.permissionButtons = payload
        }
    },
    actions: {
        async FETCH_MENULIST({ commit }) {
            //发送请求获取用户菜单名
            let res = await getMenuList()
                //调用recursionRoutes 计算出用户的路由配置
            if (res.data.state && res.data.menuList.length > 0) {
                let userMenu = recursionRoutes(res.data.menuList, allRoutes)
                    //再提交给mutataion
                commit("SET_SIDEMENU", userMenu)
            }

        }
    },
    modules: {},
});